package com.mail.result;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class AuthTokenAspect {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /// @Around是可以改变controller返回值的
    @Around("execution(* org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        // 放行
        OauthResponse response = new OauthResponse();
        ObjectMapper mapper = new ObjectMapper();
        try {
            Object proceed = pjp.proceed();
            if (proceed != null) {
                ResponseEntity<OAuth2AccessToken> responseEntity = (ResponseEntity<OAuth2AccessToken>)proceed;
                OAuth2AccessToken body = responseEntity.getBody();
                if (responseEntity.getStatusCode().is2xxSuccessful()) {
                    response.setCode("200");
                    response.setMsg("");
                    response.setData(body);
                } else {
                    logger.error("error:{}", responseEntity.getStatusCode().toString());
                    response.setCode("400");
                    response.setMsg("获取token失败");
                }
            }
        } catch (Exception e){
            response.setCode("400");
            response.setMsg("获取token失败");
        }
        String result = mapper.writeValueAsString(response);
        return ResponseEntity
                .status(200)
                .body(response);
    }
}
